package com.woniu.guoguo.controller;


import com.woniu.guoguo.common.EncryptUtil;
import com.woniu.guoguo.common.Result;
import com.woniu.guoguo.model.Invite;
import com.woniu.guoguo.model.User;
import com.woniu.guoguo.service.IInviteService;
import com.woniu.guoguo.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.net.ssl.HandshakeCompletedEvent;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Richie
 * @since 2020-11-03
 */
@RestController
@Slf4j
@CrossOrigin("*")
public class UserController {

    @Autowired
    private IUserService userService;
    @Autowired
    private IInviteService iInviteService;

    @RequestMapping("login")
    public Result login(String phone, String password, HttpSession session, HttpServletResponse response) {
        log.info("{}", phone);
        String p = EncryptUtil.encrypt(password);
        System.out.println(p);
        try {
            Subject subject = SecurityUtils.getSubject();

            subject.login(new UsernamePasswordToken(phone, password));
            User user = userService.getuser(phone);
            session.setAttribute("userid", user.getUserId());
            System.out.println(user.getUsername());
            session.setAttribute("username", user.getUsername());

            Cookie usernameCookie = new Cookie("username", user.getUsername());
            usernameCookie.setMaxAge(889200);
            Cookie userIdCookie = new Cookie("userId", user.getUserId() + "");
            userIdCookie.setMaxAge(889200);
            Cookie passCookie = new Cookie("password", password);
            passCookie.setMaxAge(889200);
            Cookie phoneCookie = new Cookie("phone", phone);
            phoneCookie.setMaxAge(889200);

            response.addCookie(usernameCookie);
            response.addCookie(userIdCookie);
            response.addCookie(passCookie);
            response.addCookie(phoneCookie);

            return Result.success(1);
        } catch (AuthenticationException e) {
            log.info("登录失败", e);
            return Result.fail("登录失败，用户名或者密码不正确");
        }


//        User user=userService.getuser(phone);
//        System.out.println(user);
//        if (user!=null&&user.getPassword()==p&&user.getUsername()==username){
//            session.setAttribute("user",user);
//            return Result.success("登录成功");
//        }else{
//            System.out.println("登录失败");
//            return Result.success("登录失败");
//        }
    }

    @RequestMapping("register")
    public Result register(String phone, String username, String password, String code) {
        log.info("邀请码：{}", code);
        //        生成邀请码
        int maxNum = 36;
        int i;
        int count = 0;
        char[] str = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
                'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
                'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
        StringBuffer invitationCode1 = new StringBuffer("");
        Random r1 = new Random();
        while (count < 8) {
            i = Math.abs(r1.nextInt(maxNum));
            if (i >= 0 && i < str.length) {
                invitationCode1.append(str[i]);
                count++;
            }
        }
        String invitationCode = invitationCode1.toString();
        String p = EncryptUtil.encrypt(password);
        int a = 0;
        try {
            User user = userService.getuser(phone);
            if (user != null) {
                a = 2;
            } else {
                int r = userService.adduser(phone, username, p, invitationCode);
                User invite = userService.findInvite(code);
                if (invite != null) {
                    //给被邀请人添加邀请人id
                    User newuser = userService.getuser(phone);
                    newuser.setUpstreamUserId(invite.getUserId());
                    userService.addinvite(newuser);
                    //更新邀请表
                    Invite invite1 = new Invite();
                    invite1.setInviteUserid(invite.getUserId());
                    invite1.setInvitedUserid(newuser.getUserId());
                    invite1.setInvitedName(newuser.getUsername());
                    iInviteService.addinvition(invite1);
                }
                if (r == 1) {
                    a = 1;
                } else {
                    a = 3;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            a = 2;
        }
        return Result.success(a);
    }

    @GetMapping("queryUser")
    public Result query(int userId) {
        User user = userService.changeUser(userId);
        return Result.success(user);
    }

    @GetMapping("changeUser")
    public Result changeInfo(User user) {
        userService.changeInfo(user);
        return Result.success();
    }

    @GetMapping("/checkLoginStatus")
    public Result checkLoginStatus(HttpSession session, HttpServletRequest request) {
        System.out.println(session.getAttribute("username"));
        if (session.getAttribute("username") != null && !((String) session.getAttribute("username")).equals("")) {
            String username = (String) session.getAttribute("username");
            Integer userId = (Integer) session.getAttribute("userid");
            System.out.println(username);
            Map<String, Object> loginName = new HashMap<>();
            loginName.put("username", username);
            loginName.put("userId", userId);
            return Result.success(loginName);
        } else {
            Cookie[] cookies = request.getCookies();
            boolean flag = false;
            Map<String, Object> loginName = new HashMap<>();
            String phone = "", password = "";

            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("userId")) {
                    Integer userId;
                    userId = Integer.parseInt(cookie.getValue());
                    session.setAttribute("userid", userId);
                    loginName.put("userId", userId);
                    flag = true;
                } else if (cookie.getName().equals("username")) {
                    session.setAttribute("username", cookie.getValue());
                    loginName.put("username", cookie.getValue());
                } else if (cookie.getName().equals("phone")) {
                    phone = cookie.getValue();
                } else if (cookie.getName().equals("password")) {
                    password = cookie.getValue();
                }
            }

            if (flag) {
                Subject subject = SecurityUtils.getSubject();
                subject.login(new UsernamePasswordToken(phone, password));
                return Result.success(loginName);
            } else {
                System.out.println("未登录");
                return Result.fail("未登录");
            }
        }
    }

    @GetMapping("/logout")
    public Result logout(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        log.info("用户退出登录");
        session.removeAttribute("userid");
        session.removeAttribute("username");

        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("userId") || cookie.getName().equals("username") || cookie.getName().equals("phone") || cookie.getName().equals("password")) {
                cookie.setMaxAge(0);
                response.addCookie(cookie);
            }
        }

        Subject subject = SecurityUtils.getSubject();
        subject.logout();

        return Result.success();
    }

}

